extends Node

# 游戏优化管理器
# 负责处理游戏性能优化、UI优化和音效管理

# 性能优化参数
@export var enable_object_pooling: bool = true  # 启用对象池
@export var max_active_enemies: int = 50  # 最大同时存在的敌人数量
@export var max_active_effects: int = 20  # 最大同时存在的特效数量
@export var cull_distance: float = 1000.0  # 超出此距离的对象将被回收
@export var physics_fps_cap: int = 60  # 物理帧率上限

# UI优化参数
@export var show_fps_counter: bool = false  # 显示FPS计数器
@export var dynamic_ui_scaling: bool = true  # 动态UI缩放
@export var ui_animation_quality: int = 2  # UI动画质量 (0=低, 1=中, 2=高)

# 音效参数
@export var master_volume: float = 0.8  # 主音量
@export var music_volume: float = 0.7  # 音乐音量
@export var sfx_volume: float = 0.9  # 音效音量
@export var enable_dynamic_audio: bool = true  # 启用动态音频

# 对象池
var enemy_pool = {}
var effect_pool = {}
var projectile_pool = {}

# 音频播放器引用
var music_player: AudioStreamPlayer
var sfx_players = []
var current_music: String = ""

func _ready():
	# 初始化对象池
	if enable_object_pooling:
		initialize_object_pools()
	
	# 设置物理帧率
	Engine.physics_ticks_per_second = physics_fps_cap
	
	# 初始化音频系统
	initialize_audio_system()
	
	# 设置UI缩放
	if dynamic_ui_scaling:
		apply_ui_scaling()
	
	# 创建FPS计数器
	if show_fps_counter:
		create_fps_counter()
	
	# 应用优化设置
	apply_optimization_settings()

func _process(delta):
	# 更新FPS计数器
	if show_fps_counter and has_node("FPSCounter"):
		$FPSCounter.text = "FPS: " + str(Engine.get_frames_per_second())
	
	# 对象池管理
	if enable_object_pooling:
		manage_object_pools()

func initialize_object_pools():
	# 初始化敌人对象池
	var enemy_types = ["DesertSlime", "DesertScorpion", "DesertSkeleton", "ForestGoblin", "ForestSpider", "ForestWolf", "SnowWolf", "SnowGolem", "IceElemental"]
	for type in enemy_types:
		enemy_pool[type] = []
	
	# 初始化特效对象池
	var effect_types = ["SandstormEffect", "OasisEffect", "RainEffect", "FogEffect", "MushroomEffect", "BlizzardEffect", "AvalancheEffect", "IcePatchEffect"]
	for type in effect_types:
		effect_pool[type] = []
	
	# 初始化投射物对象池
	var projectile_types = ["FireballProjectile", "IceSpikeProjectile", "BoneProjectile", "BandageProjectile", "SnowballProjectile"]
	for type in projectile_types:
		projectile_pool[type] = []
	
	print("对象池初始化完成")

func manage_object_pools():
	# 回收超出视野的敌人
	var player = get_tree().get_first_node_in_group("player")
	if player:
		var player_pos = player.global_position
		
		# 检查敌人
		var enemies = get_tree().get_nodes_in_group("enemies")
		if enemies.size() > max_active_enemies:
			# 按距离排序
			enemies.sort_custom(func(a, b): return player_pos.distance_to(a.global_position) > player_pos.distance_to(b.global_position))
			
			# 回收最远的敌人
			for i in range(max_active_enemies, enemies.size()):
				recycle_enemy(enemies[i])
		
		# 检查特效
		var effects = get_tree().get_nodes_in_group("effects")
		if effects.size() > max_active_effects:
			# 按距离排序
			effects.sort_custom(func(a, b): return player_pos.distance_to(a.global_position) > player_pos.distance_to(b.global_position))
			
			# 回收最远的特效
			for i in range(max_active_effects, effects.size()):
				recycle_effect(effects[i])

func recycle_enemy(enemy):
	if not is_instance_valid(enemy):
		return
	
	var type = enemy.get_script().get_path().get_file().get_basename()
	if enemy_pool.has(type):
		enemy.visible = false
		enemy.set_process(false)
		enemy.set_physics_process(false)
		if enemy.has_method("disable_collision"):
			enemy.disable_collision()
		
		enemy_pool[type].append(enemy)
		enemy.get_parent().remove_child(enemy)
		print("回收敌人: " + type)

func recycle_effect(effect):
	if not is_instance_valid(effect):
		return
	
	var type = effect.get_script().get_path().get_file().get_basename()
	if effect_pool.has(type):
		effect.visible = false
		effect.set_process(false)
		
		effect_pool[type].append(effect)
		effect.get_parent().remove_child(effect)
		print("回收特效: " + type)

func get_enemy_from_pool(type):
	if not enemy_pool.has(type) or enemy_pool[type].size() == 0:
		return null
	
	var enemy = enemy_pool[type].pop_back()
	enemy.visible = true
	enemy.set_process(true)
	enemy.set_physics_process(true)
	if enemy.has_method("enable_collision"):
		enemy.enable_collision()
	
	print("从对象池获取敌人: " + type)
	return enemy

func get_effect_from_pool(type):
	if not effect_pool.has(type) or effect_pool[type].size() == 0:
		return null
	
	var effect = effect_pool[type].pop_back()
	effect.visible = true
	effect.set_process(true)
	
	print("从对象池获取特效: " + type)
	return effect

func initialize_audio_system():
	# 创建音乐播放器
	music_player = AudioStreamPlayer.new()
	music_player.bus = "Music"
	music_player.volume_db = linear_to_db(music_volume)
	add_child(music_player)
	
	# 创建音效播放器池
	for i in range(8):
		var sfx_player = AudioStreamPlayer.new()
		sfx_player.bus = "SFX"
		sfx_player.volume_db = linear_to_db(sfx_volume)
		add_child(sfx_player)
		sfx_players.append(sfx_player)
	
	# 设置音频总线
	AudioServer.set_bus_volume_db(AudioServer.get_bus_index("Master"), linear_to_db(master_volume))
	
	print("音频系统初始化完成")

func play_music(music_name):
	if current_music == music_name:
		return
	
	var music_path = "res://asset/audio/music/" + music_name + ".ogg"
	var music = load(music_path)
	if music:
		# 淡出当前音乐
		if music_player.playing:
			var tween = create_tween()
			tween.tween_property(music_player, "volume_db", -80.0, 1.0)
			tween.tween_callback(func():
				music_player.stream = music
				music_player.volume_db = linear_to_db(music_volume)
				music_player.play()
				current_music = music_name
			)
		else:
			music_player.stream = music
			music_player.volume_db = linear_to_db(music_volume)
			music_player.play()
			current_music = music_name
		
		print("播放音乐: " + music_name)

func play_sound(sound_name, volume_scale = 1.0, pitch_scale = 1.0):
	var sound_path = "res://asset/audio/sfx/" + sound_name + ".wav"
	var sound = load(sound_path)
	if sound:
		# 查找可用的音效播放器
		for player in sfx_players:
			if not player.playing:
				player.stream = sound
				player.volume_db = linear_to_db(sfx_volume * volume_scale)
				player.pitch_scale = pitch_scale
				player.play()
				return
		
		# 如果所有播放器都在使用中，使用第一个
		sfx_players[0].stream = sound
		sfx_players[0].volume_db = linear_to_db(sfx_volume * volume_scale)
		sfx_players[0].pitch_scale = pitch_scale
		sfx_players[0].play()
		
		print("播放音效: " + sound_name)

func apply_ui_scaling():
	# 获取UI根节点
	var ui_root = get_tree().get_first_node_in_group("ui")
	if ui_root:
		# 根据屏幕分辨率调整UI缩放
		var screen_size = get_viewport().get_visible_rect().size
		var base_size = Vector2(1280, 720)
		var scale_factor = min(screen_size.x / base_size.x, screen_size.y / base_size.y)
		
		ui_root.scale = Vector2(scale_factor, scale_factor)
		print("应用UI缩放: " + str(scale_factor))

func create_fps_counter():
	var fps_counter = Label.new()
	fps_counter.name = "FPSCounter"
	fps_counter.text = "FPS: 0"
	fps_counter.position = Vector2(10, 10)
	add_child(fps_counter)

func apply_optimization_settings():
	# 设置渲染质量
	get_viewport().msaa_3d = Viewport.MSAA_DISABLED
	get_viewport().screen_space_aa = Viewport.SCREEN_SPACE_AA_DISABLED
	
	# 设置阴影质量
	get_viewport().shadow_atlas_size = 2048
	
	# 设置LOD
	get_tree().lod_min_distance = 5.0
	get_tree().lod_min_hysteresis = 0.1
	get_tree().lod_max_distance = 500.0
	get_tree().lod_max_hysteresis = 0.1
	
	# 设置物理处理
	Physics2DServer.set_active(true)
	
	print("应用优化设置完成")

func set_master_volume(volume):
	master_volume = clamp(volume, 0.0, 1.0)
	AudioServer.set_bus_volume_db(AudioServer.get_bus_index("Master"), linear_to_db(master_volume))

func set_music_volume(volume):
	music_volume = clamp(volume, 0.0, 1.0)
	if music_player:
		music_player.volume_db = linear_to_db(music_volume)

func set_sfx_volume(volume):
	sfx_volume = clamp(volume, 0.0, 1.0)
	for player in sfx_players:
		player.volume_db = linear_to_db(sfx_volume)
